package com.fzk.controller.interceptor;

import com.fzk.controller.DownloadController;
import com.fzk.controller.IndexController;
import com.fzk.controller.LoginController;
import com.fzk.router.AutoRegister;
import com.fzk.router.Interceptor;
import com.fzk.router.MyRequestMapping;
import com.fzk.server.HttpResponseUtil;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;

/**
 * 跨域请求控制
 *
 * @author uestcfzk
 * @datetime 2023-04-14 23:49:20
 */
@SuppressWarnings("unused")
@AutoRegister
public class MyInterceptor {
    // 跨域控制拦截器
    @MyRequestMapping(path = "/*", method = "OPTIONS")
    private final Interceptor corsInterceptor = (ctx, request, params) -> {
        ctx.info(String.format("OPTIONS预检请求, uri: %s", request.uri()));

        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT, Unpooled.EMPTY_BUFFER);
        response.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*").add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE").add(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE, 60 * 60 * 24 * 30);// 一个月
        HttpResponseUtil.sendAndCleanupConnection(ctx.getChannelCtx(), HttpUtil.isKeepAlive(request), response);// 响应浏览器
        return false;
    };

    // demo
    @MyRequestMapping(path = "/*", method = {"GET", "POST"})
    private final Interceptor helloInterceptor = (ctx, request, params) -> {
        ctx.info(String.format("拦截器执行, uri: %s, method: %s, params: %s", request.uri(), request.method(), params));
        return true;
    };

    /**
     * 登录校验拦截器
     */
    @MyRequestMapping(path = {"/fs/api/*", "/fs/data/personal/*"}, method = {"GET", "POST"})
    private final Interceptor checkLoginInterceptor = (ctx, request, params) -> {
        // 静态资源下载uri不拦截
        if (request.uri().startsWith(LoginController.loginApiUri)) {
            return true;
        } else if (request.uri().startsWith(DownloadController.downloadApiUri)) {
            return true;
        }
        // 校验请求合法性
        if (!LoginController.validateToken(ctx, request)) {
            // 重定向到登录页面
            HttpResponseUtil.sendPageRedirect(ctx.getChannelCtx(), request, IndexController.loginPageUri);
            return false;
        }
        return true;
    };
}
